package com.fast.alden.portal.security;

import com.fast.alden.portal.security.component.PortalTokenAuthenticationFilter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity(debug = true)
@Slf4j
public class PortalSecurityConfig {
    @Resource
    private PortalTokenAuthenticationFilter portalTokenAuthenticationFilter;
    @Resource
    private AccessDeniedHandler accessDeniedHandler;
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Resource
    private UserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/v1.0/portal/**").authorizeHttpRequests(registry -> {
            registry.anyRequest().permitAll();
        });

        // 允许跨域
        http.cors(withDefaults());

        // 关闭csrf，防止通过伪造用户请求来访问受信用站点的非法请求访问
        http.csrf(AbstractHttpConfigurer::disable);

        // 使用无状态session
        http.sessionManagement(httpSecuritySessionManagementConfigurer -> {
            httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        });

        // 指定使用的UserDetailsService
        http.userDetailsService(userDetailsService);

        // 用户名密码校验前加入token校验
        http.addFilterBefore(portalTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // 禁用security默认的登录退出
        http.formLogin(AbstractHttpConfigurer::disable);
        http.logout(AbstractHttpConfigurer::disable);

        // 设置异常处理
        http.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {
            httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler);
            httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(authenticationEntryPoint);
        });

        return http.build();
    }
}
